package clientFrame;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.List;
import java.awt.Panel;
import java.awt.TextArea;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextArea;
import javax.swing.JTextField;


public class ClientInterface extends JFrame {

	/**
	 * Class ClientInterface create all graphical component that will compose
	 * the interface
	 * 
	 * @author Jonathan VARANI & Antoine THOMAS
	 */

	private SimpleClient client;
	private ClientPrive listeClientPrive[]= new ClientPrive[50];
	private int numeroClientPrive = 0;

	private JTextField login = new JTextField();
	private JPasswordField mdp = new JPasswordField();
	private JTextArea converse = new JTextArea();
	private JTextField message = new JTextField();
	private JTextField nom = new JTextField();
	private JTextField pass = new JTextField();
	private JTextField mail = new JTextField();
	private List buddy = new List(20, false);
	private List blockMe = new List(10, false);
	private List iBlock = new List(10, false);
	private JButton envoyer;
	private JButton connecter;
	private JButton signUp;
	private JButton whoIBlock;	
	private JButton whoBlockMe;
	private JPanel identification;
	private JPanel conversation;
	private JPanel option;
	private JPanel whoBlock;
	private JPanel inscription;
	private JLabel blocker = new JLabel("Contacts qui me bloquent :");
	private JLabel blocked = new JLabel("Contacts que je bloque :");
	private JLabel sInscrire = new JLabel("S'inscrire :");
	private JLabel seConnecter = new JLabel("Se connecter :");
	private JLabel l_login = new JLabel("login : ");
	private JLabel l_mdp = new JLabel("mot de passe : ");
	private JLabel l_nom = new JLabel("login : ");
	private JLabel l_pass = new JLabel("mot de passe : ");	
	private JLabel l_mail = new JLabel("email : ");

	public ClientInterface(String host, int port) {
		super("OCSF Client");

		client = new SimpleClient(host, port, this);

		try {
			// JFrame properties
			this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
			// this.setLocale(java.util.Locale.getDefault());
			this.setResizable(true);
			this.setTitle("Tchat - Client");
			this.setSize(320, 600);
			// this.setSize(screenSize.width, screenSize.height);
			// this.setLocation( 0 , 0 );
			this.setLayout(null);
			// this.setExtendedState(JFrame.MAXIMIZED_BOTH );

			sInscrire.setPreferredSize(new Dimension(240, 40));
			seConnecter.setPreferredSize(new Dimension(240, 40));
			login.setPreferredSize(new Dimension(120, 30));
			nom.setPreferredSize(new Dimension(120, 30));
			pass.setPreferredSize(new Dimension(120, 30));
			mail.setPreferredSize(new Dimension(120, 30));
			mdp.setPreferredSize(new Dimension(120, 30));
			converse.setPreferredSize(new Dimension(380, 220));
			converse.setLineWrap(true);
			message.setPreferredSize(new Dimension(230, 30));
			envoyer = new JButton("Envoyer");
			envoyer.setPreferredSize(new Dimension(80, 30));
			whoIBlock = new JButton("Rafraichir");
			whoIBlock.setPreferredSize(new Dimension(120, 30));
			whoBlockMe = new JButton("Rafraichir");
			whoBlockMe.setPreferredSize(new Dimension(120, 30));
			connecter = new JButton("Se connecter");
			connecter.setPreferredSize(new Dimension(110, 30));
			signUp = new JButton("S'enregistrer");
			signUp.setPreferredSize(new Dimension(110, 30));
			blocker.setFont(new Font("Serif", Font.PLAIN, 12));
			blocked.setFont(new Font("Serif", Font.PLAIN, 12));

			identification = new JPanel(new FlowLayout());
			conversation = new JPanel(new FlowLayout());
			option = new JPanel(new FlowLayout());
			whoBlock = new JPanel(new FlowLayout());
			inscription = new JPanel(new FlowLayout());
			identification.setBounds(30, 40, 240, 150);
			inscription.setBounds(30, 260, 240, 200);
			whoBlock.setBounds(600, 40, 120, 480);
			option.setBounds(10, 40, 160, 400);
			
			conversation.setBounds(140, 40, 450, 360);
			/*
			 * messages = new JPanel(new FlowLayout()); messages.setBounds(170,
			 * 50, this.getScreenSize().width-170,
			 * this.getScreenSize().height-50);
			 */
			
			identification.add(seConnecter);
			identification.add(l_login);
			identification.add(login);
			identification.add(l_mdp);
			identification.add(mdp);
			identification.add(connecter);
			
			option.add(buddy);
			
			conversation.add(converse);
			conversation.add(message);
			conversation.add(envoyer);
			
			whoBlock.add(blocker);
			whoBlock.add(blockMe);
			whoBlock.add(whoBlockMe);
			whoBlock.add(blocked);
			whoBlock.add(iBlock);
			whoBlock.add(whoIBlock);
			
			inscription.add(sInscrire);
			inscription.add(l_nom);
			inscription.add(nom);
			inscription.add(l_pass);
			inscription.add(pass);
			inscription.add(l_mail);
			inscription.add(mail);
			inscription.add(signUp);
			
			this.add(option);
			this.add(identification);
			this.add(inscription);
			this.add(conversation);
			this.add(whoBlock);
			
			option.setVisible(false);
			conversation.setVisible(false);
			whoBlock.setVisible(false);

			addWindowListener(new WindowAdapter() {
				public void windowClosing(WindowEvent e) {
					quit();
				}
			});

			/*
			 * quitB.addActionListener(new ActionListener() { public void
			 * actionPerformed(ActionEvent e) { quit(); } });
			 * 
			 * closeB.addActionListener(new ActionListener() { public void
			 * actionPerformed(ActionEvent e) { close(); } });
			 */

			connecter.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					open();
				}
			});			
			signUp.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					inscrire();
				}
			});

			envoyer.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					send();
				}
			});
			whoIBlock.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					whoIBlock();
				}
			});
			buddy.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					
					if(e.getActionCommand().startsWith(">")) {
						openClientPrive(buddy.getSelectedItem());
					}
					else {
						
						if(JOptionPane.showConfirmDialog(null, "Envoyer une demande d'ami?", "Demande d'ami", JOptionPane.YES_NO_OPTION) == 0 )
							try {
								client.sendToServer("BUDDYREQUEST---" + e.getActionCommand());
							} catch (IOException e1) {
								// TODO Auto-generated catch block
								e1.printStackTrace();
							}
					}
					
				}
			});

			/*
			 * sendB.addActionListener(new ActionListener() { public void
			 * actionPerformed(ActionEvent e) { send(); } });
			 */

		} catch (Exception e) {
			System.err
					.println("<ServerInterface> - Error while creating interface : "
							+ e);
			e.printStackTrace();
		}
	}

	/*
	 * private void readFields() { int p = Integer.parseInt(port.getText());
	 * 
	 * client.setPort(p); client.setHost(host.getText()); }
	 * 
	 * public void close() { try { readFields(); client.closeConnection(); }
	 * catch (Exception ex) { liste.add(ex.toString());
	 * liste.makeVisible(liste.getItemCount()-1);
	 * liste.setBackground(Color.red); } }
	 */
	public void inscrire() {
		try {
			client.openConnection();
			client.setAction("SIGNUP");
			client.sendToServer("SIGNUP---"+nom.getText()+"---"+pass.getText()+"---"+mail.getText());
		}

		catch (Exception ex) {
			System.out.println(ex.toString());
			/*
			 * liste.add(ex.toString());
			 * liste.makeVisible(liste.getItemCount()-1);
			 * liste.setBackground(Color.red);
			 */
		}
	}
	public void open() {
		try {
			/* readFields(); */
			if (!client.isConnected())
				client.openConnection();
			client.setAction("LOGIN");
			client.sendToServer("LOGIN---" + login.getText() + "---"+ mdp.getText());
			client.sendToServer("CONNECTED");
		}

		catch (Exception ex) {
			System.out.println(ex.toString());
			/*
			 * liste.add(ex.toString());
			 * liste.makeVisible(liste.getItemCount()-1);
			 * liste.setBackground(Color.red);
			 */
		}
	}
	
	public void openClientPrive(String nom) {
		try {
			if (rechercherInList(nom)==null)
			{
				listeClientPrive[numeroClientPrive]=new ClientPrive(nom.trim(), this);
				listeClientPrive[numeroClientPrive].setVisible(true);
				listeClientPrive[numeroClientPrive].setTitle("Conversation de "+login.getText()+" - "+nom);
				if (listeClientPrive[numeroClientPrive].getBloque())
					listeClientPrive[numeroClientPrive].setTextButtonBloquer("Debloquer ce contact");
				else
					listeClientPrive[numeroClientPrive].setTextButtonBloquer("Bloquer ce contact");
				numeroClientPrive+=1;
			}
			else
			{
				rechercherInList(nom).setVisible(true);
				rechercherInList(nom).setTitle("Conversation de "+login.getText()+" - "+nom);
				if (rechercherInList(nom).getBloque())
					rechercherInList(nom).setTextButtonBloquer("Debloquer ce contact");
				else
					rechercherInList(nom).setTextButtonBloquer("Bloquer ce contact");
			}

		}

		catch (Exception ex) {
			System.out.println(ex.toString());
			/*
			 * liste.add(ex.toString());
			 * liste.makeVisible(liste.getItemCount()-1);
			 * liste.setBackground(Color.red);
			 */
		}
	}
	public void send() {
		try {
			// readFields();
			client.setAction("SEND");
			client.sendToServer("SEND---all---string---" + message.getText());
			this.message.setText("");
		}

		catch (Exception ex) {
			System.out.println(ex.toString());
			/*
			 * liste.add(ex.toString());
			 * liste.makeVisible(liste.getItemCount()-1);
			 * liste.setBackground(Color.yellow);
			 */
		}
	}
	public void whoIBlock() {
		try {
			// readFields();
			client.setAction("WHOIBLOCK");
			client.sendToServer("WHOIBLOCK");
		}

		catch (Exception ex) {
			System.out.println(ex.toString());
			/*
			 * liste.add(ex.toString());
			 * liste.makeVisible(liste.getItemCount()-1);
			 * liste.setBackground(Color.yellow);
			 */
		}
	}

	public void quit() {
		this.dispose();
	}
	
	public void addList(String nom)
	{
		listeClientPrive[numeroClientPrive]=new ClientPrive(nom.trim(), this);
		numeroClientPrive++;
	}
	
	public Boolean isInList(String n)
	{
		Boolean resultat = false;
		for (int i = 0 ; i<listeClientPrive.length ; i++)
			if (listeClientPrive[i]==null)
				break;
			else
				if (listeClientPrive[i].getNom().equals(n.trim()))
					resultat = true;
		
		return resultat;
	}	
	
	public ClientPrive rechercherInList(String n)
	{
		ClientPrive resultat = null;
		for (int i = 0 ; i<listeClientPrive.length ; i++)
			if (listeClientPrive[i]==null)	
				break;
			else
				if (listeClientPrive[i].getNom().equals(n.trim()))
					resultat = listeClientPrive[i];			
		
		return resultat;
	}

	/*
	 * public void accept() { try { BufferedReader fromConsole = new
	 * BufferedReader(new InputStreamReader(System.in)); String message;
	 * 
	 * while (true) { message = fromConsole.readLine();
	 * client.handleMessageFromClientUI(message); } } catch (Exception ex) {
	 * System.out.println ("Unexpected error while reading from console!"); } }
	 */

	/**
	 * This method overrides the method in the ChatIF interface. It displays a
	 * message onto the screen.
	 * 
	 * @param message
	 *            The string to be displayed.
	 */
	public void display(String message) {
		System.out.println("> " + message);
	}

	// GETTER AND
	// SETTER***********************************************************************
	public SimpleClient getClient() {
		return client;
	}

	public void setLogin(JTextField l) {
		this.login = l;
	}

	public JTextField getLogin() {
		return login;
	}

	public void setMdp(JPasswordField m) {
		this.mdp = m;
	}

	public JPasswordField getMdp() {
		return mdp;
	}

	public void setClient(SimpleClient c) {
		this.client = c;
	}

	public void setIdentification(JPanel p) {
		this.identification = p;
	}

	public JPanel getIdentification() {
		return identification;
	}

	public void setConversation(JPanel p) {
		this.conversation = p;
	}

	public JPanel getConversation() {
		return conversation;
	}
	public void setOption(JPanel o) {
		this.option = o;
	}

	public JPanel getOption() {
		return option;
	}	
	public JPanel getInscription() {
		return inscription;
	}
	public void setConverse(JTextArea c) {
		this.converse = c;
	}

	public JTextArea getConverse() {
		return converse;
	}
	public void setBuddy(List b) {
		this.buddy = b;
	}
	public List getBuddy() {
		return buddy;
	}
	public void setWhoBlock(JPanel b) {
		this.whoBlock = b;
	}
	public JPanel getWhoBlock() {
		return whoBlock;
	}
	public void setConversePrive(String msg, String nom)
	{
		rechercherInList(nom).getConverse().setText(rechercherInList(nom).getConverse().getText()+nom+" dit :\n"+msg+"\n");
	}
	public List getBlockMe() {
		return blockMe;
	}
	public List getIBlock() {
		return iBlock;
	}
	public void setTextNom(String s)
	{
		nom.setText(s);
	}
	public void setTextPass(String s)
	{
		pass.setText(s);
	}
	public void setTextMail(String s)
	{
		mail.setText(s);
	}

	// main
	public static void main(String[] args) {

		String host = "";
		int port = 0; // The port number

		try {
			host = args[0];
		} catch (ArrayIndexOutOfBoundsException e) {
			host = "localhost";
		}
		ClientInterface chat = new ClientInterface(host, 5555);
		chat.setVisible(true);
		// chat.accept(); //Wait for console data

	}

}
